package com.winz.cultureapp.utils;

import android.widget.TextView;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class CountDownManager {
	
	private int count;
	private OnFinishedListener listener;

	public CountDownManager startCount(final TextView tv,int time){
		count = time;
		Observable<Integer> observable = Observable.create(new ObservableOnSubscribe<Integer>() {
			@Override
			public void subscribe(@NonNull ObservableEmitter<Integer> e) throws Exception {
				while (true){
					if (count>=0){
						Thread.sleep(1000);
						e.onNext(count--);
					}else{
						e.onComplete();
						break;
					}
				}
			}
		});
		observable.subscribeOn(Schedulers.io())
				.observeOn(AndroidSchedulers.mainThread())
				.subscribe(new Observer<Integer>() {
					@Override
					public void onSubscribe(@NonNull Disposable d) {

					}

					@Override
					public void onNext(@NonNull Integer integer) {
						tv.setText(integer+"");
					}

					@Override
					public void onError(@NonNull Throwable e) {

					}

					@Override
					public void onComplete() {
						if (listener != null){
							listener.onFinished();
						}
					}
				});
		return this;
	}

	public void setOnFinishedListener(OnFinishedListener listener){
		this.listener = listener;
	}
	public interface OnFinishedListener{
		void onFinished();
	}

}
